package juc;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * @author 乔巴
 * @date 2021/7/29 9:56
 **/
public class CountDownLatchTest {

    public static void main(String[] args) throws InterruptedException {
        test1();
        test2();
    }

    private static void test2() throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(1);

        Thread 大乔 = new Thread(() -> waitToFight(countDownLatch));
        Thread 兰陵王 = new Thread(() -> waitToFight(countDownLatch));
        Thread 安其拉 = new Thread(() -> waitToFight(countDownLatch));
        Thread 哪吒 = new Thread(() -> waitToFight(countDownLatch));
        Thread 铠 = new Thread(() -> waitToFight(countDownLatch));

        大乔.start();
        兰陵王.start();
        安其拉.start();
        哪吒.start();
        铠.start();
        System.out.println("敌方还有5秒达到战场，全军出击！");
        Thread.sleep(5000);
        countDownLatch.countDown();
    }

    private static void waitToFight(CountDownLatch countDownLatch) {
        try {
            countDownLatch.await(); // 在此等待信号再继续
            System.out.println("收到，发起进攻！");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

    private static void test1() throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(5);
        Thread  thread1 = new Thread(()->{
            System.out.println("thread1准备就位");
            latch.countDown();
        });
        Thread  thread2 = new Thread(()->{
            System.out.println("thread2准备就位");
            latch.countDown();
        });
        Thread  thread3 = new Thread(()->{
            System.out.println("thread3准备就位");
            latch.countDown();
        });
        Thread  thread4 = new Thread(()->{
            System.out.println("thread4准备就位");
            latch.countDown();
        });
        Thread  thread5 = new Thread(()->{
            try {
                System.out.println("thread5:稍等我去上个厕所");
                Thread.sleep(5000);
                System.out.println("thread5准备就位");
                latch.countDown();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        thread1.start();
        thread2.start();
        thread3.start();
        thread4.start();
        thread5.start();
        latch.await(10, TimeUnit.SECONDS);
        System.out.println("所有线程已经就位！");
    }
}
